package com.simplenix.nicasio.sys;

import com.simplenix.nicasio.def.Module;
import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.FileUtil;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author fronald
 */
public class InitTaskManager {

	private static InitTaskManager itm;

	private List<InitTask> tasks;

	public static InitTaskManager getInstance() throws AppException {
		if (itm == null) {
			itm = new InitTaskManager();
		}
		return itm;
	}

	private InitTaskManager() throws AppException {
		try {
			tasks = new ArrayList<InitTask>();
			List<Module> modules = SystemDef.getInstance().getModules().getModulesList();
			for (Module module : modules) {
				String pkg = module.getBasePackage();
				List<String> classes = FileUtil.getClassList(pkg + ".init");
				for (String className : classes) {
					Class c = Class.forName(className);
					InitTask initTask = (InitTask) c.newInstance();
					this.tasks.add(initTask);
				}
			}
		} catch (InstantiationException e) {
			throw new AppException(e);
		} catch (ClassNotFoundException e) {
			throw new AppException(e);
		} catch (IllegalAccessException e) {
			throw new AppException(e);
		}
	}

	public void executeAll() throws AppException {
		for (InitTask task : this.tasks) {
			task.doInit();
		}
	}

}
